using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Sustainalytics.Synchronization.Interface;
using Sustainalytics.SharedEntities.EsgResearch;

namespace Sustainalytics.ClientDW.Synchronization.SyncESGData.RPIndicatorExtendedLogic
{
    public class RPIndicatorExtendedProcessor
    {
        private readonly Dictionary<string, IndicatorTemplate> indicatorTemplates;

        private readonly IDictionary<Guid, Dictionary<string, int?>> historicalDataIndicatorsDictionary;

        private readonly ILogger logger;

        public RPIndicatorExtendedProcessor(Dictionary<string, IndicatorTemplate> indicatorTemplates, CompanyHistoricalDataIndicatorsDictionary historicalDataIndicatorsDictionary, ILogger logger)
        {
            this.indicatorTemplates = indicatorTemplates;
            this.logger = logger;
            this.historicalDataIndicatorsDictionary = historicalDataIndicatorsDictionary;
        }

        public void AddIndicatorInformation(IList<RPIndicatorExtended> extendedIndicators)
        {
            Parallel.ForEach(extendedIndicators, indicator =>
            {
                AddIndicatorTemplateInformation(indicator);

                AddOutlookInformation(indicator);

            });
        }

        private void AddIndicatorTemplateInformation(RPIndicatorExtended indicator)
        {
            IndicatorTemplate indicatorTemplate;

            if (indicatorTemplates.TryGetValue(indicator.Number, out indicatorTemplate))
            {
                indicator.Template = indicatorTemplate;
                indicator.TemplateId = indicatorTemplate.Id;
            }
            else
            {
                throw new Exception($"Indicator template for {indicator.Number} was not found in {typeof(IndicatorTemplate).Name} collection");
            }
        }

        private void AddOutlookInformation(RPIndicatorExtended indicator)
        {
            int? trend = null;
            var historicalDataIndicators = historicalDataIndicatorsDictionary.ContainsKey(indicator.CompanyId)
                ? historicalDataIndicatorsDictionary[indicator.CompanyId]
                : null;
            if (historicalDataIndicators != null)
            {
                var rawScore = historicalDataIndicators.ContainsKey(indicator.Number)
                    ? historicalDataIndicators[indicator.Number]
                    : null;

                if (rawScore != null)
                {
                    trend = 0;
                    if (indicator.SelectedAnswer.Score > rawScore)
                    {
                        trend = 1;
                    }
                    if (indicator.SelectedAnswer.Score < rawScore)
                    {
                        trend = -1;
                    }
                }
            }
            indicator.Trend = trend;
        }
    }
}